package  {
	import flash.events.KeyboardEvent;
	import org.papervision3d.materials.ColorMaterial;
	import org.papervision3d.objects.primitives.Plane;
	import org.papervision3d.objects.primitives.Sphere;
	import org.papervision3d.view.BasicView;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import org.papervision3d.view.stats.StatsView;
	[ SWF( backgroundColor = '#000000', width = '600', height = '400', frameRate='60' ) ]
	public class LsystemMorph extends BasicView {
		
		private var isDragging:Boolean = false;
		private var stats:StatsView; 
		
		private var ground:Plane;
		private var plant:Plant;
		private var testSphere:Sphere = new Sphere(new ColorMaterial(0xff0000), 200);
		private var counter:int = 0;
		
		public var numIterations:uint = 3;
		
		
		public function LsystemMorph() {
			super(600, 600, false, false, "CAMERA3D");
			preparePv3d();
			createMaterials();
			createObjects();
			addListeners();
			startRendering();
		}
		
		public function preparePv3d():void {
			camera.y = 600;
			camera.zoom = 4;
			stats = new StatsView(renderer);
			stage.addChild(stats);
		}
		
		public function createMaterials():void {
			
		}
		public function createObjects():void {
			ground = new Plane (new ColorMaterial(0xDCC0A8), 1000, 1000, 5, 5);
			ground.rotationX = -90;
			ground.y = -600;
			scene.addChild(ground);
			plant = new Plant( 800, numIterations );

			scene.addChild(plant);
		}

		public function addListeners():void {
			stage.addEventListener(MouseEvent.MOUSE_DOWN, onPressHandler);
			stage.addEventListener(MouseEvent.MOUSE_UP, onMouseUpHandler);
			stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
		}
		override protected function onRenderTick(event:Event=null):void
		{
			plant.draw( 0, -600, 0 );
			rotateCamera();
			super.onRenderTick(event);
		}
		
		private function reset() {
			trace(counter++);
			// Preventing memory leaks
			plant.containerForDrawing.material.unregisterObject(plant.containerForDrawing); // -25 kb
			plant.containerForDrawing.material.destroy(); // -15 kb
			plant.removeChild(plant.containerForDrawing); // -5kb
			scene.removeChild(plant);
			plant = new Plant( 800, numIterations );
			scene.addChild(plant);
		}
		
		private function rotateCamera():void{
			if(isDragging){
				var x:Number = (stage.mouseX - stage.stageWidth/2) / 4;
				camera.moveLeft(x);
				var y:Number = (stage.mouseY - stage.stageHeight/2) / 6;
				camera.moveDown(y);
				if (camera.y > 1000 || camera.y < -200) camera.moveDown(-y);
			}
		}
		public function onPressHandler(event:MouseEvent):void {
			isDragging = true;
		}
		public function onMouseUpHandler(event:MouseEvent):void {
			isDragging = false;
		}
		public function keyUpHandler(e:KeyboardEvent):void {
			trace(e.charCode);
			if(e.charCode == 32)
				reset();
		}
	}
}